import { computed } from 'vue'
import { useStore } from 'vuex'

// 创建兼容Vue2和Vue3的Vuex辅助函数
export function useMapState(mapper) {
  const store = useStore()
  const storeStateFns = {}

  Object.keys(mapper).forEach(key => {
    const mapFn = mapper[key]
    storeStateFns[key] = computed(() => mapFn(store.state))
  })

  return storeStateFns
}

export function useMapActions(actions) {
  const store = useStore()
  const mappedActions = {}

  actions.forEach(action => {
    mappedActions[action] = payload => store.dispatch(action, payload)
  })

  return mappedActions
}

// 为选项式API提供兼容层
export const mapState = mapper => {
  return Object.keys(mapper).reduce((prev, key) => {
    const fn = mapper[key]
    prev[key] = function () {
      return fn(this.$store.state)
    }
    return prev
  }, {})
}

export const mapActions = actions => {
  return actions.reduce((prev, action) => {
    prev[action] = function (payload) {
      return this.$store.dispatch(action, payload)
    }
    return prev
  }, {})
}
